// pages/address_edit/index.js
Page({
  data: {
    navBarHeight: 0,
    contentTop: 0,
    bottomSafeArea: 0,
    
    // 编辑模式：add(新增) 或 edit(编辑)
    editMode: 'add',
    
    // 地址ID（编辑模式下使用）
    addressId: '',
    
    // 表单数据
    formData: {
      receiver: '',
      phoneNumber: '',
      region: [],
      detail: '',
      isDefault: false
    },
    
    // 省市区选择器数据
    regionData: [],
    
    // 表单验证错误
    errors: {},
    
    // 提交状态
    submitting: false
  },

  onLoad(options) {
    // 计算导航栏高度和底部安全区域
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    const navBarHeight = statusBarHeight + 44
    const bottomSafeArea = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
    
    this.setData({
      navBarHeight,
      contentTop: navBarHeight,
      bottomSafeArea
    })
    
    // 判断编辑模式
    const addressId = options.id
    if (addressId) {
      this.setData({
        editMode: 'edit',
        addressId
      })
      this.loadAddressDetail(addressId)
    } else {
      this.setData({
        editMode: 'add',
        'formData.isDefault': true // 新增地址默认勾选设为默认地址
      })
    }
    
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: addressId ? '编辑地址' : '新增地址'
    })
  },

  // 加载地址详情（编辑模式）
  async loadAddressDetail(addressId) {
    try {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      
      const result = await wx.cloud.callFunction({
        name: 'getAddressDetail',
        data: { addressId }
      })
      
      if (result.result.success) {
        const address = result.result.data
        this.setData({
          formData: {
            receiver: address.receiver || '',
            phoneNumber: address.phoneNumber || '',
            region: address.region || [],
            detail: address.detail || '',
            isDefault: address.isDefault || false
          }
        })
      } else {
        throw new Error(result.result.message || '获取地址详情失败')
      }
    } catch (error) {
      console.error('加载地址详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } finally {
      wx.hideLoading()
    }
  },

  // 收货人姓名输入
  onReceiverInput(e) {
    this.setData({
      'formData.receiver': e.detail.value,
      'errors.receiver': ''
    })
  },

  // 手机号输入
  onPhoneInput(e) {
    this.setData({
      'formData.phoneNumber': e.detail.value,
      'errors.phoneNumber': ''
    })
  },

  // 详细地址输入
  onDetailInput(e) {
    this.setData({
      'formData.detail': e.detail.value,
      'errors.detail': ''
    })
  },

  // 省市区选择
  onRegionChange(e) {
    this.setData({
      'formData.region': e.detail.value,
      'errors.region': ''
    })
  },

  // 默认地址开关
  onDefaultChange(e) {
    this.setData({
      'formData.isDefault': e.detail.value
    })
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data
    const errors = {}
    let isValid = true

    // 验证收货人姓名
    if (!formData.receiver.trim()) {
      errors.receiver = '请输入收货人姓名'
      isValid = false
    } else if (formData.receiver.trim().length < 2) {
      errors.receiver = '收货人姓名至少2个字符'
      isValid = false
    }

    // 验证手机号
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!formData.phoneNumber.trim()) {
      errors.phoneNumber = '请输入手机号'
      isValid = false
    } else if (!phoneRegex.test(formData.phoneNumber.trim())) {
      errors.phoneNumber = '请输入正确的手机号'
      isValid = false
    }

    // 验证省市区
    if (!formData.region || formData.region.length !== 3 || !formData.region[0] || !formData.region[1] || !formData.region[2]) {
      errors.region = '请选择省市区'
      isValid = false
    }

    // 验证详细地址
    if (!formData.detail.trim()) {
      errors.detail = '请输入详细地址'
      isValid = false
    } else if (formData.detail.trim().length < 5) {
      errors.detail = '详细地址至少5个字符'
      isValid = false
    }

    this.setData({ errors })
    return isValid
  },

  // 保存地址
  async saveAddress() {
    if (this.data.submitting) return

    // 表单验证
    if (!this.validateForm()) {
      wx.showToast({
        title: '请检查输入信息',
        icon: 'none'
      })
      return
    }

    this.setData({ submitting: true })

    try {
      wx.showLoading({
        title: '保存中...',
        mask: true
      })

      const { formData, editMode, addressId } = this.data
      
      // 构建地址数据
      const addressData = {
        receiver: formData.receiver.trim(),
        phoneNumber: formData.phoneNumber.trim(),
        region: formData.region,
        detail: formData.detail.trim(),
        isDefault: formData.isDefault
      }

      let result
      if (editMode === 'edit') {
        // 编辑地址
        result = await wx.cloud.callFunction({
          name: 'updateAddress',
          data: {
            addressId,
            ...addressData
          }
        })
      } else {
        // 新增地址
        result = await wx.cloud.callFunction({
          name: 'createAddress',
          data: addressData
        })
      }

      if (result.result.success) {
        // 更新本地缓存
        if (formData.isDefault) {
          const addressToCache = {
            ...addressData,
            _id: editMode === 'edit' ? addressId : result.result.addressId
          }
          wx.setStorageSync('defaultAddress', addressToCache)
          wx.setStorageSync('addressCacheTime', Date.now())
        }
        
        wx.hideLoading()
        wx.showToast({
          title: editMode === 'edit' ? '修改成功' : '添加成功',
          icon: 'success'
        })

        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        throw new Error(result.result.message || '保存失败')
      }
    } catch (error) {
      console.error('保存地址失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none'
      })
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 返回按钮
  handleBack() {
    wx.navigateBack()
  }
})